package dp;

/**
 * Created With IntelliJ IDEA.
 * Descriptions:最长公共子序列
 * author: Mr.Du
 * Date: 2023/3/31
 * Time: 17:13
 */
public class LongestCommonSubsequence {

    public static void main(String[] args) {
//        int res = longestCommonSubsequence("psnw", "vozsh");
//        System.out.println(res);
        int res = longestCommonSubsequence1("abcde", "ace");
        System.out.println(res);
    }


    public static int longestCommonSubsequence(String s1, String s2) {
        int len1 = s1.length();
        int len2 = s2.length();
        int[][] dp = new int[len1 + 1][len2 + 1];
        for(int i = 1;i < dp.length;i++){
            for(int j = 1;j < dp[0].length;j++){
                if(s1.charAt(i-1) == s2.charAt(j - 1)){
                    dp[i][j] = dp[i - 1][j - 1] + 1;
                }else{
                    dp[i][j] = Math.max(dp[i - 1][j], dp[i][j-1]);
                }
            }
        }
        return dp[len1][len2];
    }

    /**
     * 垃圾做法
     * @param s1
     * @param s2
     * @return
     */
    public static int longestCommonSubsequence1(String s1, String s2) {
        int[][] dp = new int[s2.length()][s1.length()];
        for(int i = 0;i < s1.length();i++){
            if(s1.charAt(i) == s2.charAt(0)){
                dp[0][i] = 1;
            }else if(i > 0){
                dp[0][i] = dp[0][i - 1];
            }
        }

        for(int i = 0;i < s2.length();i++) {
            if (s1.charAt(0) == s2.charAt(i)) {
                dp[i][0] = 1;
            } else if (i > 0) {
                dp[i][0] = dp[i - 1][0];
            }
        }
        for(int i = 1; i < s2.length(); i++){
            for(int j = 1; j < s1.length(); j++){
                if(s2.charAt(i) == s1.charAt(j)){
                    dp[i][j] = dp[i - 1][j - 1] + 1;
                }else{
                    dp[i][j] = Math.max(dp[i][j - 1],dp[i - 1][j]);
                }
            }
        }
        return dp[s2.length() - 1][s1.length() - 1];
    }
}

